<?php

declare (strict_types = 1);

namespace app\common\service;

use app\common\service\BaseService;
use app\common\exception\AdminException;
use app\common\repository\CodexPriceRepository;
use think\facade\Log;
use think\Http;

class CodexPriceService extends BaseService
{
   public function __construct(CodexPriceRepository $repository)
   {
       $this->repository = $repository;
   }

    /**
     * 获取列表
     *
     * @param array $data
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function getList(array $data = []): array
    {
        [$page, $pageSize] = $this->getPaginationParams();
        $where = [];
        if(!empty($data['price'])) {
            $where['price'] = $data['price'];
        }
        return $this->repository->paginate($where, ['create_time' => 'desc'], $page, $pageSize);
    }

    /**
     * 获取详情信息
     *
     * @param $id
     * @return \app\common\model\BaseModel|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo($id): ?\app\common\model\BaseModel
    {
        return $this->repository->getOne($id);
    }

    /**
     * 创建信息
     *
     * @param array $data
     * @return \app\common\model\BaseModel|array
     * @throws \Exception
     */
    public function create(array $data): \app\common\model\BaseModel|array
    {
        return $this->repository->save($data);
    }

    /**
     * 更新信息
     * 
     * @param array $data
     * @param $id
     * @return bool|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update(array $data, $id): bool|int
    {
        if(empty($id)) {
            throw new AdminException('ID 不能为空');
        }
        return $this->repository->update($data, $id);
    }

    /**
     * 删除信息
     *
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete($id): bool
    {
        return $this->repository->delete($id);
    }

    /**
     * 获取最新价格
     *
     * @return mixed
     */
    public function getNewPrice(): mixed
    {
        return $this->repository->getNewPrice();
    }

    /**
     * 获取codex价格历史
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function getCodexPriceHistory(): array
    {
        [$page, $pageSize] = $this->getPaginationParams();
        return $this->repository->paginate([], ['create_time' => 'desc'], $page, $pageSize);
    }


    /**
     * 同步价格
     *
     * @return array
     */
    public function syncCodexPrice(): array
    {
        $date = date('Y-m-d');
        $filePath = root_path() . 'codex-scraper/price_' . $date . '.json';
        // ✅ 2. 检查文件是否存在
        if (!file_exists($filePath)) {
            throw new AdminException("数据文件不存在: " . $filePath . "，请检查爬虫是否已生成");
        }
        $data = file_get_contents(root_path() . 'codex-scraper/price_' . $date . '.json');
        // 将 JSON 字符串转为 PHP 数组（第二个参数 true 表示转为关联数组）
        $priceData = json_decode($data, true);

        // 检查是否解析成功
        if (json_last_error() !== JSON_ERROR_NONE) {
            // 可选：抛出异常或返回错误
            return ['error' => 'JSON 解析失败: ' . json_last_error_msg()];
        }

        // 3. 格式化数据，准备插入
        $insertData = [];
        foreach ($priceData as $item) {
            // 确保字段存在
            if (empty($item['id']) || empty($item['symbol']) || !isset($item['price']) || empty($item['time'])) {
                continue; // 跳过无效数据
            }

            $insertData[] = [
                'api_id'      => $item['id'],
                'symbol'      => trim($item['symbol']),
                'price'       => (float)$item['price'],
                'create_time' => strtotime($item['time']) ?: time(),
            ];
        }

        if (empty($insertData)) {
            throw new AdminException('无可插入数据');
        }

        // 4. 批量插入，重复时更新（可选）或跳过
        try {
            // 方法2：推荐：使用 ON DUPLICATE KEY UPDATE（ThinkPHP 支持）
            \think\facade\Db::name('codex_price')->replace()->strict(false)->insertAll($insertData);

            return [
                'message' => '数据导入成功',
                'count'   => count($insertData)
            ];

        } catch (\Exception $e) {
            // 捕获重复插入等错误
            throw new AdminException('导入失败: ' . $e->getMessage(), 500);
        }
    }
}